import { defineCustomElement, type App } from "vue";
import { ElIcon } from "element-plus";
import { Document } from '@element-plus/icons-vue'
import { Component } from "vue";

let flyingIconApp: App | null = null;

function clickElement(e: HTMLElement): void;
function clickElement(e: MouseEvent): void;
function clickElement(e: any) {
  console.log(e)
  console.log(e instanceof MouseEvent)
  console.log(e instanceof HTMLElement)
  if (!document.querySelector("#exportFileListShortcut")) {
    console.log("导出通知动画：未找到目标飞行元素")
    return
  }

  const iconWidth = 50;
  const iconHeight = 50;
  let iconTop = 0;
  let iconLeft = 0;
  if (e instanceof HTMLElement) {
    const eElementRect = e.getBoundingClientRect(); 
    iconTop = eElementRect.y - iconHeight / 2;
    iconLeft = eElementRect.x - iconWidth / 2;
  }

  if (e instanceof MouseEvent) {
    iconTop = e.clientY - iconHeight / 2;
    iconLeft = e.clientX - iconWidth / 2;
  }

  const movingTime = 1000 //ms

  const flyingIcon: Component = {
    template: `
      <div class="flying-icon" style="top: ${iconTop}px; left: ${iconLeft}px;" ref="flyingIcon">
        <el-icon><Document /></el-icon>
      </div>
    `,
    mounted() {
      nextTick(() => {
        this.flyIcon();
      })
    },

    beforeUnmount() {
      clearTimeout(this.displayNoneDelayTimer)
    },

    displayNoneDelayTimer: null,

    methods: {
      flyIcon() {
        const targetElement = document.querySelector("#exportFileListShortcut")
        if (!targetElement) {
          console.log("导出通知：未找到目标元素")
          return
        }
        const targetElementRect = targetElement.getBoundingClientRect();
        const { x, y, width, height } = targetElementRect

        const flyIconRect = this.$refs["flyingIcon"].getBoundingClientRect();
        const {width: fWidth, height: fHeight} = flyIconRect;
        // console.log(flyIconRect)
        // console.log(targetElementRect)
        const finalX = x - (fWidth - width) / 2
        const finalY = y - (fHeight - height) / 2

        console.log("mounted this", finalX, finalY);
        this.$refs["flyingIcon"].style.setProperty("top", finalY + 'px');
        this.$refs["flyingIcon"].style.setProperty("left", finalX + 'px');
        this.$refs["flyingIcon"].style.setProperty("transform", 'scale(0.5)');
        this.$refs["flyingIcon"].style.setProperty("opacity", '0.5');

        this.displayNoneDelayTimer = setTimeout(() => {
          this.$refs["flyingIcon"].style.setProperty("display", 'none');
          flyingIconApp?.unmount();
          document.querySelector(".icon-container")?.remove();
        
          const event = new CustomEvent("noticeexportevent")
          document.dispatchEvent(event) 
        }, movingTime);

      }
    }
  }

  const domArr = [...document.all].map(element => +window.getComputedStyle(element).zIndex || 2)
  const maxZIndex = Math.max(...domArr) + 1

  // 默认样式
  if (!document.querySelector('#flyingIconClass')) {
    const flyingIconClassTag = document.createElement("style");
    flyingIconClassTag.setAttribute("id", 'flyingIconClass');
    flyingIconClassTag.setAttribute("type", 'text/css');
    flyingIconClassTag.innerHTML = `
      .flying-icon {
        position: absolute;
        width: ${iconWidth}px;
        height: ${iconHeight}px;
        background: #001E70;
        z-index: ${maxZIndex};
        transition: all ${movingTime}ms ease-in;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        color: white;
        font-weight: bold;
      }

      :deep(.el-icon) {
        font-size: 40px;
      }
    `
    document.head.append(flyingIconClassTag)
  }

  // 为了使用ElIcon 组件，新创建个实例
  flyingIconApp = createApp(flyingIcon)
  flyingIconApp.component('ElIcon', ElIcon);
  flyingIconApp.component('Document', Document)

  const iconContainer = document.createElement("div");
  iconContainer.classList.add("icon-container");
  flyingIconApp.mount(iconContainer);
  document.body.append(iconContainer);
} 


/**
 * 文件导出动画到顶部的图标
 */
export const noticeExport = {
  mounted(el: HTMLElement, binding: { value?: {shouldNotice: boolean}}) {
    // console.log("directive el", el)
    if (binding?.value?.shouldNotice === undefined) {
      el.addEventListener("click", clickElement)
    }
  },

  updated(el: HTMLElement, binding: { value?: {shouldNotice: boolean}, oldValue?: {shouldNotice: boolean}}) {
    // console.log("value", binding)
    if (binding.oldValue?.shouldNotice === false && binding.value?.shouldNotice === true) { // avoid undefined situation
      clickElement(el)
    }
  },

  beforeUnmount(el: HTMLElement) {
    el.removeEventListener('click', clickElement)
  },
}